package moe.cat.com.moelight.Manger;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Build;

import moe.cat.com.moelight.Utils.MyApplication;

public class Flashlight {
 public  static     CameraManager manager;
    public  static   Camera camera = null;
    public  static   Camera.Parameters parameters = null;

    /**
     * 打开相机辅助方法 适配新版系统
     * @param context
     * @param isChecked
     */
    public static void  OpenFlashlight(Context context,boolean isChecked){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //android6.0调用的手电筒接口
            try {
                manager     = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

                String[] ids  = manager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = manager.getCameraCharacteristics(id);
                    //查询该摄像头组件是否包含闪光灯
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    /*
                     * 获取相机面对的方向
                     * CameraCharacteristics.LENS_FACING_FRONT 前置摄像头
                     * CameraCharacteristics.LENS_FACING_BACK 后只摄像头
                     * CameraCharacteristics.LENS_FACING_EXTERNAL 外部的摄像头
                     */
                    Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
                    if (flashAvailable != null && flashAvailable
                            && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                        //打开或关闭手电筒
                        manager.setTorchMode(id,isChecked);
                    }
                }


            }catch(CameraAccessException e){
                e.printStackTrace();
            }
        }else{
            //低于6.0系统的手电筒
            if ( isChecked){
                camera = Camera.open();
                parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);// 开启
                camera.setParameters(parameters);
                camera.startPreview();
            }else{
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);// 关闭
                camera.setParameters(parameters);
                camera.stopPreview();
                camera.release();
            }

        }

    }
}
